<?php

class UserController extends Zend_Controller_Action {

    public function init() {
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->initView();
    }

    public function indexAction() {
        
    }

    public function loginAction() {

        if ($this->getRequest()->isXmlHttpRequest()) {
            //diable layout and view rendering as Ajax is used
            $this->_helper->viewRenderer->setNoRender();
            $this->_helper->layout->disableLayout();

            if ($this->getRequest()->isPost()) {

                $loginForm = new Application_Form_Login();
                if ($loginForm->isValid($this->getRequest()->getParams())) {

                    $email = $loginForm->getValue("loginEmail");
                    $password = $loginForm->getValue("loginPassword");
                    $remember = $loginForm->getValue("remember");

                    //set up the auth adapter
                    // get the default db adapter
                    $db = Zend_Db_Table::getDefaultAdapter();

                    //create the auth adapter
                    $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'user', 'email', 'password');
                    //set the email and password
                    $authAdapter->setIdentity($email);
                    $authAdapter->setCredential(md5($password));
                    //authenticate
                    $result = $authAdapter->authenticate();
			//$session_info = new Zend_Session_Namespace("myinfo");
			//$session_info->ali = 5;
                    if ($result->isValid()) {
                        $auth = Zend_Auth::getInstance();
                        $storage = $auth->getStorage();
                        $storage->write($authAdapter->getResultRowObject(array('email', 'id', 'roleId', 'firstName', 'lastName', 'image', 'isEnabled')));
                        $userInfo = $auth->getIdentity();
                        if (!$userInfo->isEnabled) {
                            $response = array("loginStatus" => "failed", "message" => "Sorry, but your account is deactivated");
                            $auth->clearIdentity();
                            return $this->_helper->json($response);
                        }
                        $seconds  = 60 * 60 * 24 * 30; // one month
                        if ($remember) {
                            $saveHandler = Zend_Session::getSaveHandler(); 
                            $saveHandler->setLifetime($seconds) 
                                        ->setOverrideLifetime(true);
                            Zend_Session::RememberMe($seconds);
                        } else {
                            Zend_Session::ForgetMe();
                        }
                        $response = array("loginStatus" => "success");
                        return $this->_helper->json($response);
                    } else {

                        $response = array("loginStatus" => "failed", "message" => "Sorry, your email or password was incorrect");
                        return $this->_helper->json($response);
                    }
                } else {

                    $response = array("loginStatus" => "failed", "message" => "Sorry, Please Eneter a vaild Email");
                    return $this->_helper->json($response);
                }
            }
        }
    }

    public function logoutAction() {
        $authAdapter = Zend_Auth::getInstance();
        $authAdapter->clearIdentity();
        $this->redirect("/index/index");
    }

    public function profileAction() {
        // action body
    }

    public function registerAction() {
        if (!empty($this->view->identity)) {
            $this->redirect("/");
        }
        $userForm = new Application_Form_Registration();
        $this->view->form = $userForm;
        $user = OSD_Facebook::getUser();

        if ($user) {
            try {
                $userProfile = OSD_Facebook::api('/me', 'GET');
                $this->view->logoutUrl = OSD_Facebook::getLogoutUrl();
            } catch (FacebookApiException $e) {
                $loginUrl = OSD_Facebook::getLoginUrl(array('scope' => 'email'));
                $this->view->loginUrl = $loginUrl;
            }
        } else {

            // No user, print a link for the user to login
            $loginUrl = OSD_Facebook::getLoginUrl(array('scope' => 'email'));

            $this->view->loginUrl = $loginUrl;
        }
        if (!empty($userProfile)) {

            $data = array();
            $data['firstName'] = $userProfile['first_name'];
            $data['lastName'] = $userProfile['last_name'];
            $data['email'] = $userProfile['email'];
            $data['gender'] = $userProfile['gender'];
            if (!empty($userProfile['work']))
                $data['jobTitle'] = $userProfile['work'][0]['position']['name'] . "@" . $userProfile['work'][0]['employer']['name'];
            $data['facebook'] = $userProfile['link'];
            $userForm->populate($data);
        }
        if ($this->getRequest()->isPost()) {
            if ($userForm->isValid($this->getRequest()->getParams())) {
                $userModel = new Administration_Model_User();
                //add RoleId and isEnabled
                $userInfo = $userForm->getValues();
                $userInfo['roleId'] = 3;
                $userInfo['isEnabled'] = 1;

                $userId = $userModel->addUser($userInfo);

                if ($userId) {

                    $this->_flashMessenger->addMessage('User added successfully!');
                    $this->redirect("/");
                }
            } else {
                $this->view->errors = $userForm->getMessages();
            }
        }
    }

}
